<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html{
            scroll-behavior: smooth;
        }

        body {
            height: 6000px;
        }

        div {
            display: none;
            position: fixed;
            right: 0;
            top: 50%;
            transform: translateY(-100%);
            width: 60px;
            height: 300px;
            background-color: #ccc;
        }
    </style>
</head>

<body>
    <div>
        <button>回到顶部</button>
    </div>
    <script>
        // 获取元素
        const div = document.querySelector("div")
        // 添加scroll事件
        window.addEventListener("scroll", function () {
            // 拿到html元素滚动的顶部距离
            const scrollTop = document.documentElement.scrollTop
            if (scrollTop >= 1000) {
                // 拿到html元素滚动的顶部距离>=1000侧边栏则显示
                div.style.display = "block"
            } else {
            // 拿到html元素滚动的顶部距离<=1000侧边栏则隐藏
                div.style.display = "none"
            }
        })

        document.querySelector("button").addEventListener("click", function () {
            //window.scrollTo(0,0) 
            //页面回到顶部
            document.documentElement.scrollTop = 0
        })
    </script>
</body>

</html>